angular.module('chat.controllers', ['ionic.contrib.frostedGlass'])
.controller('NoticeCtrl', function($scope, $timeout,$ionicTabsDelegate, $ionicScrollDelegate,$cordovaCapture,ChatService) {

	$scope.$on('$ionicView.enter', function(e) {
		$ionicTabsDelegate.$getByHandle('im-tabs').showBar(false);

		
		var chatSubHandle = $scope.subscribe('chats',function(){
			return [{'is_notice':true}];
		});
		$scope.helpers({
			theSession: function() {
			  return Chats.findOne({'is_notice':true});
			},
			messages: function() {
			  return Messages.find({'chat_id': $scope.theSession._id});
			}
		});
		
		$timeout(function() {
			$ionicScrollDelegate.scrollBottom(false);
		}, 1);
	});
  
  $scope.captureAudio = function() {
		var options = { limit: 3, duration: 50 };

    $cordovaCapture.captureAudio(options).then(function(audioData) {
      
      console.log(mediaFiles[i].fullPath + " " +mediaFiles[i].name);
    }, function(err) {
      
    });
  };

	$scope.data = {}; 
  $scope.sendMessage = function(){
		ChatService.sendMessage($scope);
	 
	 
 };

	

	$scope.inputUp = function() {
		$timeout(function() {
			$ionicScrollDelegate.$getByHandle('chatScroll').scrollBottom(true);
		}, 300);
	};
	$scope.inputDown = function() {
		$ionicScrollDelegate.$getByHandle('chatScroll').resize();
	};

  $scope.isText = true;
  $scope.toggleBar = function(){
    $scope.isText = !$scope.isText;
  };
})


.controller('ImContactsCtrl', function($scope, $ionicTabsDelegate, $ionicModal) {
	$scope.$on('$ionicView.enter', function(e) {

		$ionicTabsDelegate.$getByHandle('im-tabs').showBar(true);
	  var usersSubHandle = $scope.subscribe('users');
	  
	  $scope.helpers({
	    imContacts: function () {
	      return Meteor.users.find(
					{_id: { '$ne': Meteor.userId()},state:{'$in':['已启用','锁定中']} },
					{fields:{profile:1}});
	    }
	  });
	});
})

.controller('ImContactsDetailCtrl', function($scope, $ionicTabsDelegate, $stateParams) {
	$scope.$on('$ionicView.enter', function(e) {

		$ionicTabsDelegate.$getByHandle('im-tabs').showBar(false);
	  var usersSubHandle = $scope.subscribe('users');
	  
	  $scope.helpers({
	    theUser: function () {
	      return Meteor.users.findOne(
					{_id: $stateParams._id},
					{fields:{profile:1}});
	    }
	  });
		$scope.newChat = function(){

		};
	});
})

.controller('ChatsCtrl', function($scope, $ionicTabsDelegate, $ionicModal) {

	$scope.$on('$ionicView.enter', function(e) {
		$ionicTabsDelegate.$getByHandle('im-tabs').showBar(true);

		var chatSubHandle = $scope.subscribe('chats');
	  $scope.helpers({
			notice:function(){
				return Chats.find({'is_notice':true});
			},
	    chats: function () {
	      return Chats.find({'is_notice': { $exists: false } });
	    }
	  });
	});

  $ionicModal.fromTemplateUrl('templates/common/chat/new-chat.html', {
    scope: $scope
  }).then(function (modal) {
    $scope.modal = modal;
  });
  $scope.$on('$destroy', function () {
    $scope.modal.remove();
  });
  $scope.openNewChat = function () {
    $scope.modal.show();
  };
	
  $scope.remove = function (chat) {
    Meteor.call('removeChat', chat._id);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, $timeout, $ionicTabsDelegate, $ionicScrollDelegate,$cordovaCapture,ChatService) {
	$ionicTabsDelegate.$getByHandle('im-tabs').showBar(false);

	$scope.$on('$ionicView.enter', function(e) {
		var chatSubHandle = $scope.subscribe('chats',function(){
			return [{'_id':$stateParams._id}];
		});
	  $scope.helpers({
	    theSession: function () {
	      return Chats.findOne({'_id':$stateParams._id});
	    },
	    messages: function () {
	      return Messages.find({'chat_id': $scope.theSession._id });
	  	}
		});
		
		$timeout(function() {
			$ionicScrollDelegate.scrollBottom(false);
		}, 1);
	});
	
	$scope.captureAudio = function() {
		var options = { limit: 3, duration: 50 };
		$cordovaCapture.captureAudio(options).then(function(audioData) {
			
			console.log(mediaFiles[i].fullPath + " " +mediaFiles[i].name);
		}, function(err) {
			
		});
	};

	$scope.data = {}; 
	$scope.sendMessage = function(){
		ChatService.sendMessage($scope);
	};

	

	$scope.inputUp = function() {
		$timeout(function() {
			$ionicScrollDelegate.$getByHandle('chatScroll').scrollBottom(true);
		}, 300);
	};
	$scope.inputDown = function() {
		$ionicScrollDelegate.$getByHandle('chatScroll').resize();
	};

	$scope.isText = true;
	$scope.toggleBar = function(){
		$scope.isText = !$scope.isText;
	};
})


.controller('NewChatCtrl', function ($scope, $state, $meteor) {
  $scope.subscribe('users');

  $scope.helpers({
    users: function () {
      return Meteor.users.find({ _id: { $ne: Meteor.userId() } });
    }
  });

  $scope.hideModal = hideModal;
  $scope.newChat = newChat;

  

  function hideModal () {
    $scope.modal.hide();
  }

  function newChat (userId) {
    var chat = Chats.findOne({ userIds: { $all: [Meteor.userId(), userId] } });
    if (chat) {
      return goToChat(chat._id);
    }

    Meteor.call('newChat', userId, function (err, result) {
      if (err) {
        return handleError(err);
      }

      goToChat(result);
    });
  }

  function goToChat (chatId) {
    hideModal();
    return $state.go('tab.chat-detail', { chatId: chatId });
  }

  function handleError (err) {
    $log.error('new chat error ', err);
    $ionicPopup.alert({
      title: err.reason || 'Create chat fail',
      template: 'Please try again',
      okType: 'button-positive button-clear'
    });
  }
});
